from mainfunc.baseapi import BaseApi
import requests
import json
from config.fileName import title_dic_bj


class HandleFilebj(BaseApi):
    def __init__(self):
        self.url_1 = None
        self.headers = {
            "Accept": "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) "
                          "Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.42 ",
            "Referer": "http://www.bse.cn/rule/Tech_area.html",
            "X-Requested-With": "XMLHttpRequest",
            "Cookie": "Hm_lvt_ef6193a308904a92936b38108b93bd7f=1668061217,1668067330,1668408226,1668491953; "
                      "Hm_lpvt_ef6193a308904a92936b38108b93bd7f=1668499021",
            "Origin": "http://www.bse.cn",
            "Host": "www.bse.cn"
        }

        self.payload = {
            'page': '0',
            'pageSize': '20',
            'keywords': '',
            'startTime': '',
            'nodeIds[]': ['0', '1485', '1486', '1487'],
            'needFields[]': ['infoId', 'title', 'linkUrl', 'htmlUrl', 'publishDate', 'fileUrl'],
        }
        self.url = 'http://www.bse.cn/'
        self.req = requests.post(
            'https://www.bse.cn/info/listse.do?t=0.7214065565145105&callback=jQuery331_1674201013074',
            headers=self.headers, data=self.payload)
        print(self.req.text)
        self.res = self.req.text.replace('jQuery331_1674201013074(', '')[:-1]
        self.res = json.loads(self.res)[0]['data']['content']

    def downF(self):
        for fileName in list(title_dic_bj.keys()):
            isfind = False
            print(self.res)
            for i in self.res:
                if fileName in i['title']:
                    isfind = True
                    self.url_1 = self.url + i['fileUrl']
                    try:
                        fileTpye = i['fileUrl'].split('.')[-1]
                        BaseApi.cleanFile(title_dic_bj[fileName])
                        BaseApi.downFile(fileTpye, i['title'], self.url_1)
                        print(f'文件:{fileName}处理成功')
                        break
                    except Exception as e:
                        print(f'文件:{fileName}处理失败,错误信息：{e}')
            if not isfind:
                print(f"未找到文件{fileName}")


if __name__ == '__main__':
    HandleFilebj().downF()
